package cn.laixueit.service.impl;

import cn.laixueit.exception.StudentException;
import cn.laixueit.mapper.StudentMapper;
import cn.laixueit.pojo.Student;
import cn.laixueit.pojo.StudentExample;
import cn.laixueit.service.StudentService;
import cn.laixueit.utils.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;


    @Override
    public PageInfo<Student> findall(Integer startpage, Integer pagesize, Student student) {
        PageHelper.startPage(startpage,pagesize);
        StudentExample example = getCondition(student);
        List<Student> studentList = studentMapper.selectByExample(example);
        PageInfo<Student> pageInfo = new PageInfo<>(studentList);
        return pageInfo;
    }

    @Override
    public Integer deleteById(Integer id) {
        studentMapper.deleteByPrimaryKey(id);
        return null;
    }

    @Override
    public void save(Student student, String birthday) {
        // 计算年龄
        int nowyear = LocalDate.now().getYear();
        int birthYear = Utils.getYear(birthday);
        int age = nowyear- birthYear;
        student.setAge(age);
        studentMapper.insertSelective(student);
    }

    @Override
    public Student selectById(Integer id) {
        Student student = studentMapper.selectByPrimaryKey(id);
        return student;
    }

    @Override
    public void update(Student student) throws StudentException {
        try {
            studentMapper.updateByPrimaryKeySelective(student);
        }catch (Exception e){
            throw  new StudentException();
        }
    }

    /**
     * 条件拼接
     * @param student
     * @return
     */
    public StudentExample getCondition(Student student){
        StudentExample example = new StudentExample();
        example.setOrderByClause("id");
        StudentExample.Criteria criteria = example.createCriteria();
        if(student!=null){
            if(student.getName()!=null && !"".equals(student.getName().trim())){
                criteria.andNameLike("%"+student.getName()+"%");
            }
            if(student.getClassno()!=null && student.getClassno()!=0){
                criteria.andClassnoEqualTo(student.getClassno());
            }
        }
        return example;
    }
}
